package com.ruoyi.web.controller.tool;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class demo {

    public static void main(String[] args) {
//        socket();
        ByteBuf();
//        ByteBufCopy();

    }


    public static void socket() {
        try {
            Socket socket = new Socket("localhost", 8848);
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);
            printWriter.write("$tmb00035ET3318/08/22 11:5804029.94,027.25,20.00,20.00$");
            printWriter.flush();
            socket.shutdownOutput();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void ByteBuf() {
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        buf.writeBytes(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
        log(buf);
        //从buf这个总的数据中，分别拆分5个字节保存到两个ByteBuf中
        //零拷贝机制    (浅克隆)
//        ByteBuf bb1 = buf.slice(0, 5);
//        ByteBuf bb2 = buf.slice(5, 5);
//        log(bb1);
//        log(bb2);

        byte b = buf.readByte();
        byte i1 = buf.readByte();

        //废弃字节,释放已经读过的字节空间
        ByteBuf byteBuf = buf.discardReadBytes();
        int i2 = byteBuf.readByte();
        System.out.println(b + "----" + i1 + "---" + i2);

        System.out.println("修改原始数据");
        buf.setByte(2, 8);
        log(buf);
    }


    public static void ByteBufCopy() {
        ByteBuf header = ByteBufAllocator.DEFAULT.buffer();
        header.writeBytes(new byte[]{1, 2, 3, 4, 5});
        ByteBuf body = ByteBufAllocator.DEFAULT.buffer();
        body.writeBytes(new byte[]{6, 7, 8, 9, 10});
/*        ByteBuf total= Unpooled.buffer(header.readableBytes()+body.readableBytes());
        total.writeBytes(header);
        total.writeBytes(body);*/
        //从逻辑成面构建了一个总的buf数据。
        //第二个零拷贝实现
        //通过CompositeByteBuf构建了一个逻辑整体，里面仍然是两个真实对象，也就是有一个指针指向了同一个对象，所以这里类似于浅拷贝的实现
       /* CompositeByteBuf compositeByteBuf=Unpooled.compositeBuffer();
        compositeByteBuf.addComponents(true,header,body);
        log(compositeByteBuf);*/
        //Unpooled
        ByteBuf total = Unpooled.wrappedBuffer(header, body);
        log(total);
        header.setByte(2, 9);
        log(total);
    }


    private static void log(ByteBuf buf) {
        StringBuilder sb = new StringBuilder();
        sb.append(" read index:").append(buf.readerIndex());  //读索引
        sb.append(" write index:").append(buf.writerIndex()); //写索引
        sb.append(" capacity :").append(buf.capacity()); //容量
        ByteBufUtil.appendPrettyHexDump(sb, buf);
        System.out.println(sb);
    }

}
